<template>
	<div class="category-charts-container">
		<div v-if="categories.length === 0" class="empty-data">
			<el-empty description="暂无分类数据" />
		</div>
		<div v-else class="category-charts">
			<div
				v-for="category in categoriesWithData"
				:key="category.value || `category-${category.label}`"
				class="category-chart"
				ref="categoryChartRefs"
			>
				<div class="category-header">
					<h4 class="category-title">{{ category.label }}</h4>
					<div class="category-stats">
						<span class="stat-item">开工率: {{ getCategoryStartRateToToday(category) }}%</span>
						<span class="stat-item">完工率: {{ getCategoryEndRateToToday(category) }}%</span>
						<span class="stat-item">时间进度率: {{ getCategoryTimeProgressRate(category) }}%</span>
					</div>
				</div>
				<!-- 显示模式选择 -->
				<div class="display-mode-selector">
					<el-radio-group v-model="displayMode" size="small">
						<el-radio-button value="combined">合并显示</el-radio-button>
						<el-radio-button value="split">分离显示</el-radio-button>
					</el-radio-group>
				</div>
				<!-- 图表容器 -->
				<div class="category-chart-container">
					<CombinedAreaChart 
						:chart-data="category.chartData" 
						:area-name="category.label"
						:show-time-progress="true"
						:show-split-layout="displayMode === 'split'"
						ref="categoryChartComponents"
					/>
				</div>
			</div>
		</div>
		
		<!-- 显示筛选信息 -->
		<div v-if="categories.length > 0 && categoriesWithData.length === 0" class="filter-info">
			<el-alert
				title="筛选结果"
				type="info"
				:closable="false"
				show-icon
			>
				<template #default>
					<div>当前筛选条件下，所选分类暂无数据</div>
					<div class="filter-details">
						<span v-if="queryParams.workAreaId">区域: {{ getWorkAreaLabel(queryParams.workAreaId) }}</span>
						<span v-if="queryParams.workTime">月份: {{ queryParams.workTime }}</span>
					</div>
				</template>
			</el-alert>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { ref, watch, computed, nextTick, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { usePlanViewApi } from '/@/api/plans/planView';
import CombinedAreaChart from './CombinedAreaChart.vue';

interface Category {
	value: number | null;
	label: string;
	chartData: any[];
}

interface Props {
	categories: Array<{ value: number | null; label: string }>;
	queryParams: any;
	chartDataCache?: Record<number, any[]>; // 新增：图表数据缓存
}

const props = defineProps<Props>();
const planViewApi = usePlanViewApi();

const categories = ref<Category[]>([]);
const categoryChartRefs = ref<HTMLElement[]>([]);
const categoryChartComponents = ref<any[]>([]);
const displayMode = ref<'combined' | 'split'>('combined');

// 只显示有数据的分类
const categoriesWithData = computed(() => {
	console.log('[DEBUG] 计算categoriesWithData:', {
		categoriesLength: categories.value.length,
		categories: categories.value
	});
	
	const result = categories.value.filter(category => {
		const hasChartData = category.chartData && category.chartData.length > 0;
		const hasValidData = hasChartData && category.chartData.some(item => 
			item.planStart > 0 || 
			item.planEnd > 0 || 
			item.actualStart > 0 || 
			item.actualEnd > 0
		);
		
		console.log('[DEBUG] 分类过滤结果:', {
			categoryLabel: category.label,
			categoryValue: category.value,
			hasChartData: hasChartData,
			chartDataLength: category.chartData?.length || 0,
			hasValidData: hasValidData,
			sampleChartData: category.chartData?.[0] || null
		});
		
		return hasChartData && hasValidData;
	});
	
	console.log('[DEBUG] 最终categoriesWithData:', result);
	return result;
});

// 获取区域名称
const getWorkAreaLabel = (workAreaId: number | null) => {
	if (!workAreaId) return '';
	// 这里可以从props中获取区域数据，或者通过API获取
	return `区域${workAreaId}`;
};

// 为每个分类加载图表数据 - 完全依赖Store缓存
const loadCategoryChartData = async () => {
	console.log('[DEBUG] 开始加载分类图表数据:', {
		categoriesLength: props.categories.length,
		categories: props.categories,
		hasChartDataCache: !!props.chartDataCache,
		chartDataCacheKeys: props.chartDataCache ? Object.keys(props.chartDataCache) : []
	});
	
	const promises = props.categories.map(async (category) => {
		try {
			// 完全依赖缓存数据，不再有API fallback
			const chartData = props.chartDataCache && category.value ? 
				(props.chartDataCache[category.value] || []) : [];
			
			console.log('[DEBUG] 处理分类数据:', {
				categoryLabel: category.label,
				categoryValue: category.value,
				foundCacheData: !!props.chartDataCache?.[category.value!],
				chartDataLength: chartData.length,
				sampleChartData: chartData[0] || null
			});
			
			return {
				...category,
				chartData: chartData
			};
		} catch (error) {
			console.error(`加载分类 ${category.label} 数据失败:`, error);
			return {
				...category,
				chartData: []
			};
		}
	});

	try {
		const results = await Promise.all(promises);
		categories.value = results;
		
		// 数据加载完成后，等待DOM更新并执行resize
		await nextTick();
		setTimeout(() => {
			resize();
		}, 100);
	} catch (error) {
		console.error('加载分类图表数据失败: ', error);
		ElMessage.error('加载分类图表数据失败');
	}
};

// 计算分类到今天的开工率（保留一位小数）
const getCategoryStartRateToToday = (category: Category) => {
	if (!category.chartData || category.chartData.length === 0) return 0;

	const today = new Date();
	const todayStr = today.toISOString().slice(0, 10);

	// 找到今天或最近的数据（使用最后一个<=今天的数据）
	const validData = category.chartData.filter(item => item.date <= todayStr);
	if (validData.length === 0) return 0;
	const todayData = validData[validData.length - 1];

	// 计算整个月的计划开工总数（最后一天的累计数就是总计划数）
	const lastDayData = category.chartData[category.chartData.length - 1];
	const planStartTotal = lastDayData.planStart || 0;
	if (planStartTotal === 0) return 0;

	// 保留一位小数
	const rate = (todayData.actualStart / planStartTotal) * 100;
	return Math.round(rate * 10) / 10;
};

// 计算分类到今天的完工率（保留一位小数）
const getCategoryEndRateToToday = (category: Category) => {
	if (!category.chartData || category.chartData.length === 0) return 0;

	const today = new Date();
	const todayStr = today.toISOString().slice(0, 10);

	// 找到今天或最近的数据（使用最后一个<=今天的数据）
	const validData = category.chartData.filter(item => item.date <= todayStr);
	if (validData.length === 0) return 0;
	const todayData = validData[validData.length - 1];

	// 计算整个月的计划完工总数（最后一天的累计数就是总计划数）
	const lastDayData = category.chartData[category.chartData.length - 1];
	const planEndTotal = lastDayData.planEnd || 0;
	if (planEndTotal === 0) return 0;

	// 保留一位小数
	const rate = (todayData.actualEnd / planEndTotal) * 100;
	return Math.round(rate * 10) / 10;
};

// 计算时间进度率（因领导要求需要推迟1天，但到最后一天显示100%）
const getCategoryTimeProgressRate = (category: Category) => {
	if (!category.chartData || category.chartData.length === 0) return 0;
	const today = new Date();
	const todayStr = today.toISOString().slice(0, 10);
	const totalDays = category.chartData.length;
	const passedDaysRaw = category.chartData.filter(item => item.date <= todayStr).length;

	// 如果已经到达或超过最后一天，显示100%
	if (passedDaysRaw >= totalDays) {
		return 100;
	}

	// 否则，推迟1天显示（保留至少1天的最小值）
	const passedDays = Math.max(1, passedDaysRaw - 1);
	const rate = (passedDays / totalDays) * 100;
	return Math.round(rate * 10) / 10;
};

// 暴露resize方法给父组件
const resize = () => {
	nextTick(() => {
		// 调用所有子图表组件的resize方法
		if (categoryChartComponents.value && Array.isArray(categoryChartComponents.value)) {
			categoryChartComponents.value.forEach((chartComponent, index) => {
				if (chartComponent && typeof chartComponent.resize === 'function') {
					setTimeout(() => {
						chartComponent.resize();
					}, index * 50); // 错开时间，避免同时resize
				}
			});
		}
	});
};

// 监听查询参数变化
watch(() => props.queryParams, () => {
	loadCategoryChartData();
}, { deep: true });

// 监听分类列表变化
watch(() => props.categories, () => {
	loadCategoryChartData();
}, { deep: true });

// 监听缓存数据变化
watch(() => props.chartDataCache, () => {
	loadCategoryChartData();
}, { deep: true });

// 暴露方法给父组件
defineExpose({
	resize
});

// 初始化加载
onMounted(() => {
	loadCategoryChartData();
});
</script>

<style lang="scss" scoped>
.category-charts-container {
	width: 100%;
	
	.empty-data {
		padding: 40px;
		text-align: center;
	}
	
	.filter-info {
		margin-top: 20px;
		
		.filter-details {
			margin-top: 8px;
			font-size: 12px;
			color: var(--el-text-color-secondary);
			
			span {
				margin-right: 15px;
				
				&:last-child {
					margin-right: 0;
				}
			}
		}
	}
	
	.category-charts {
		.category-chart {
			margin-bottom: 30px;
			padding: 20px;
			border: 1px solid var(--el-border-color-light);
			border-radius: 4px;
			background: var(--el-bg-color);
			box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
			
			.category-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 15px;
				
				.category-title {
					margin: 0;
					font-size: 16px;
					font-weight: 600;
					color: var(--el-text-color-primary);
				}
				
				.category-stats {
					.stat-item {
						margin-left: 15px;
						font-size: 12px;
						color: var(--el-text-color-secondary);
						
						&:first-child {
							margin-left: 0;
						}
					}
				}
			}
			
			.display-mode-selector {
				text-align: center;
				margin-bottom: 15px;
				padding-bottom: 10px;
				border-bottom: 1px solid var(--el-border-color-lighter);
			}
			
			.category-chart-container {
				height: 400px;
				background: var(--el-bg-color);
				border-radius: 4px;
				padding: 15px;
				border: 1px solid var(--el-border-color-light);
				box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
			}
		}
	}
}
</style> 